package com.bestcem.xm.user.grpc.client;

import com.bestcem.xm.common.core.constant.GrpcClientNames;
import com.bestcem.xm.push.grpc.v1.enums.PushSmsTypeEnum;
import com.bestcem.xm.push.grpc.v1.services.PushSmsServiceGrpc;
import com.bestcem.xm.push.grpc.v1.services.SendSingleSmsRequest;
import com.bestcem.xm.push.grpc.v1.services.SendSingleSmsResponse;
import com.bestcem.xm.user.grpc.client.convert.UserSmsGrpcConvert;
import com.bestcem.xm.user.grpc.client.dto.SmsSendingResultDTO;
import com.zy.dp.proto.base.v1.Code;
import lombok.extern.slf4j.Slf4j;
import net.devh.boot.grpc.client.inject.GrpcClient;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 短信服务
 *
 * @author panyun <yun.pan@idiaoyan.com>
 * @version v1.0
 * @date 2022/3/4 18:06
 */
@Slf4j
@Service(value = "SmsGrpcClientService")
public class SmsGrpcClientService {

    @GrpcClient(GrpcClientNames.DS_PUSH)
    private PushSmsServiceGrpc.PushSmsServiceBlockingStub stub;

    @Resource
    private UserSmsGrpcConvert userSmsGrpcConvert;

    public SmsSendingResultDTO sendSingleSms(String mobile, String content, String componentCode) {
        if (log.isInfoEnabled()) {
            log.info("发送短信：mobile:{} ", mobile);
        }
        SendSingleSmsRequest build = SendSingleSmsRequest.newBuilder()
                .setSmsType(PushSmsTypeEnum.PushSmsType.forNumber(2))
                .setPhone(mobile)
                .setContent(content)
                .setComponentCode(componentCode)
                .build();
        SendSingleSmsResponse response = stub.sendSingleSms(build);

        // 校验查询结果
        if (Code.ERROR_VALUE == response.getStatus().getCodeValue()) {
            log.error("发送短信失败：mobile:{} ", mobile);
            return null;
        }
        return userSmsGrpcConvert.sendSingleResultGrpc2Dto(response.getResult());
    }

}
